package com.kun.service.service;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.kun.auth.LoginUser;
import com.kun.constants.CacheConstants;
import com.kun.constants.Constants;
import com.kun.utils.AddressUtils;
import com.kun.utils.IDUtils;
import com.kun.utils.JsonUtils;
import com.kun.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    // 20 分钟的毫秒数
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    // 毫秒
    protected static final long MILLIS_SECOND = 1000;

    // 60 秒
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static SecretKey secretKey;
    private final RedisService redisService;

    public TokenService(RedisService redisService) {
        this.redisService = redisService;
    }

    @PostConstruct
    public void init() {
        secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 获取用户身份信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                return JsonUtils.toBean(redisService.getCacheObject(userKey), LoginUser.class);
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 获取请求token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            return token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }


    /**
     * 解析 Token
     */
    public Claims parseToken(String token) {
        return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload();
    }

    /**
     * 获取用户缓存 key
     */
    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 验证令牌有效期，相差不足 20分钟，自动刷新缓存
     */
    public void verifyToken(LoginUser loginUser) {
        Assert.isTrue(loginUser != null && loginUser.getUser() != null, "获取用户信息失败");
        Long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setJSONObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 创建令牌
     */
    public String createToken(LoginUser loginUser) {
        String uuid = IDUtils.getUUID();
        loginUser.setToken(uuid);
        setUserAgent(loginUser);
        refreshToken(loginUser);
        // 获取token
        return Jwts.builder()
                .claims().add(Constants.LOGIN_USER_KEY, uuid).and()
                .signWith(secretKey).compact();
    }

    /**
     * 设置用户代理信息
     */
    public void setUserAgent(LoginUser loginUser) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.isTrue(servletRequestAttributes != null, "获取请求上下文失败");
        HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();

        UserAgent userAgent = UserAgentUtil.parse(httpServletRequest.getHeader("User-Agent"));

        String ip = ServletUtil.getClientIP(httpServletRequest);
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOs().getName());
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisService.deleteObject(userKey);
        }
    }

}
